package com.cs.deviceManager.mqtt;

import com.cs.deviceManager.domain.DevDevice;
import com.cs.deviceManager.mapper.DevDeviceMapper;
import com.cs.deviceManager.device.DeviceEventListener;
import com.cs.deviceManager.mqtt.handler.DeviceEventMessageHandler;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class MqttStartupListener implements CommandLineRunner {

    private static final Logger log = LoggerFactory.getLogger(MqttStartupListener.class);

    @Resource
    private DevDeviceMapper devDeviceMapper;

    @Resource
    @Qualifier("defaultListener")
    private DeviceEventListener defaultListener;

    private List<DeviceEventListener> listeners;

    @Value("${mqtt.broker:tcp://mqtt.cssolution.cn:1883}")
    private String broker;

    @Value("${mqtt.client-id:device-status-listener}")
    private String clientId;

    @Value("${mqtt.username:}")
    private String username;

    @Value("${mqtt.password:}")
    private String password;


    public MqttStartupListener(List<DeviceEventListener> mqttListener) {
        this.listeners = mqttListener;
    }

    @Override
    public void run(String... args) {
        log.info("正在初始化 MQTT 客户端...");
        DeviceEventMessageHandler deviceStatusMessageHandler = new DeviceEventMessageHandler();
        // 注册监听器（处理上线/下线）
        deviceStatusMessageHandler.addAlListener(this.listeners);

        // 连接 MQTT Broker
        if (!MqttUtil.connect(broker, clientId, username, password)) {
            log.error("MQTT 连接失败，无法订阅主题");
            return;
        }

        log.info("MQTT 连接成功，开始订阅主题...");

        try {

            MqttUtil.startHeartbeatMonitor(60, defaultListener);

            List<DevDevice> activeDevices = devDeviceMapper.selectActiveDevices();
            log.info("发现 {} 个活跃设备，正在恢复数据主题订阅...", activeDevices.size());

            for (DevDevice device : activeDevices) {
                String dataTopic = device.getSubscribe();

                MqttUtil.subscribe(clientId, dataTopic, deviceStatusMessageHandler);
                log.debug("已订阅设备数据主题: {}", dataTopic);
            }

            // 订阅固件更新响应主题
            MqttUtil.subscribe(clientId, "device/+/data", deviceStatusMessageHandler);
            log.info("已订阅固件更新响应主题: device/+/firmware/response");
            log.info("MQTT 主题订阅初始化完成");

        } catch (Exception e) {
            log.error("MQTT 订阅过程中发生异常", e);
        }
    }
}